<template>
  <div>
    <HeaderFixed />
    <Header></Header>
    <div class="search">
      <div class="img-logo">
        <img src="@/assets/v-logo.jpg" class="v-logo">
      </div>
      <el-select 
        v-model="selVal" 
        class="m-2"
        placeholder="请选择要搜索的分类"
        @change="selValChange"
        clearable
      >
        <el-option
          v-for="item in options"
          :key="item.category_id"
          :label="item.category_name"
          :value="item.category_id"
        />
      </el-select>
    </div>
    <div
      v-for="(item) in remadeCategoryList"
      :key="item.category_id"
    >
      <categoryItem 
        :categoryTitle="item.category_name"
        :categoryList="item.category_list"
      />
    </div>
    <el-backtop :right="100" :bottom="100" />
    <Footer></Footer>
  </div>
</template>

<script setup>
// components
import Header from '@/components/common/Header.vue'
import Footer from '@/components/common/Footer.vue'
import categoryItem from '@/components/category/categoryItem.vue';
import HeaderFixed from '@/components/common/HeaderFixed.vue'

import { useStore } from "vuex";
import { onBeforeMount } from 'vue';
import bookModelApi from '@/request/api/book.js';


// 循环渲染组件
let categoryList = ref([]);
// 经过计算筛选后的list
let remadeCategoryList = ref([]);
// 供选择的分类列表
const options = ref([]);
// 绑定到select的值
let selVal = ref();

const store = useStore();

onBeforeMount(async () => {
  categoryList.value = store.state.book.cateGoryList;
  remadeCategoryList.value = categoryList.value;
  options.value = store.state.book.cateGoryList;

  for(let i = 0; i < categoryList.value.length; i++){
    categoryList.value[i].category_list = await getAllBookByCategoryId(categoryList.value[i].category_id);
  }

})


// 根据分类id category_id 获取其所有图书数据
async function getAllBookByCategoryId( cid ){
  const res = await bookModelApi.getAllBookByCategoryIdApi({
    category_id: cid
  });

  return res.data;
}


// 选择触发回调
const selValChange = val => {
  if(val == ''){
    // 全部
    remadeCategoryList.value = categoryList.value;
  }else{
    // 按条件筛选
    remadeCategoryList.value = categoryList.value.filter(item => item['category_id'] == val)
  }
}


</script>

<style lang='less' scoped>
.search{
  width: 80%;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  .img-logo{
    width: 150px;
    height: 80px;
    img{
      width: 100%;
      height: 100%;
    }
  }
}
</style>